<template>
  <!-- 保留原有 Tailwind 类，同时添加 `result-page` 作为向后兼容的类名 -->
  <div class="result-page min-h-screen bg-gradient-to-b from-white to-gray-50 py-8">
    <div class="max-w-6xl mx-auto px-4">
      <h1 class="text-2xl font-semibold text-gray-800 mb-4">支付结果</h1>

      <!-- 查询表单：支持 payment_no 和 email 联合查询 -->
      <div class="mb-4 bg-white p-4 rounded-md shadow-sm">
        <div class="flex flex-col md:flex-row gap-3 items-center">
          <input v-model="inputPaymentNo" placeholder="支付单号" class="w-full md:w-1/3 px-3 py-2 border rounded" />
          <input v-model="inputEmail" placeholder="下单邮箱" class="w-full md:w-1/3 px-3 py-2 border rounded" />
          <button @click="queryOrder" :disabled="loading" class="inline-block px-4 py-2 bg-blue-600 text-white rounded-md">
            {{ loading ? '查询中…' : '查询订单' }}
          </button>
          <button @click="clearForm" class="inline-block px-3 py-2 bg-gray-200 text-gray-800 rounded-md">清空</button>
        </div>
        <div class="mt-2 text-sm text-red-600">支付回调失败可联系邮箱处理（发送微信支付截图和订单号）：fqymcu994@outlook.com</div>
      </div>

      <div v-if="loading" class="text-gray-500">查询中，请稍候…</div>

      <div v-else>
        <div v-if="error" class="text-red-500 mb-4">{{ error }}</div>

        <div v-else>
          <!-- 如果查询到多条订单，展示列表供选择 -->
          <div v-if="orders && orders.length" class="mb-4 bg-white p-4 rounded-md shadow-sm">
            <div class="text-sm text-gray-600">查询到 {{ orders.length }} 条订单，点击查看详情：</div>
            <ul class="mt-3 space-y-3">
              <li v-for="(o, idx) in orders" :key="o.payment_no || o.payment_id" class="p-3 border rounded flex justify-between items-center">
                <div>
                  <div class="font-medium">订单号：{{ o.payment_no || o.payment_id }}</div>
                  <div class="text-sm text-gray-500">金额: ¥{{ o.amount ?? '-' }} · 状态: {{ o.status || '-' }} · {{ o.created_at || '' }}</div>
                  <div v-if="o.email" class="text-xs text-gray-400">邮箱: {{ o.email }}</div>
                </div>
                <div>
                  <button @click="selectOrder(idx)" class="px-3 py-1 bg-blue-600 text-white rounded">查看</button>
                </div>
              </li>
            </ul>
          </div>

          <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
            <div class="lg:col-span-2">
              <div class="bg-white rounded-xl shadow p-6">
                <h3 class="text-lg font-medium text-gray-800">订单号：{{ displayedOrder.payment_no || displayedOrder.payment_id }}</h3>
                <div class="mt-3 text-gray-600 space-y-2">
                  <div><strong class="text-gray-700">状态：</strong> {{ displayedOrder.status || '未知' }}</div>
                  <div><strong class="text-gray-700">金额：</strong> ¥{{ displayedOrder.amount ?? '-' }}</div>
                  <div v-if="displayedOrder.email"><strong class="text-gray-700">下单邮箱：</strong> {{ displayedOrder.email }}</div>
                  <div v-if="displayedOrder.created_at"><strong class="text-gray-700">下单时间：</strong> {{ displayedOrder.created_at }}</div>
                  <div v-if="displayedOrder.pay_method"><strong class="text-gray-700">支付方式：</strong> {{ displayedOrder.pay_method }}</div>
                  <div v-if="displayedOrder.product_name"><strong class="text-gray-700">产品名称：</strong> {{ displayedOrder.product_name }}</div>
                </div>
              </div>
            </div>

            <div>
              <div class="bg-white rounded-xl shadow p-4 detail-card">
                <h4 class="text-md font-medium text-gray-800">订单详情</h4>
                <textarea readonly class="mt-3 w-full h-48 p-3 border border-gray-100 rounded-md font-mono text-sm text-gray-700" :value="detailText"></textarea>
                <div class="mt-3 text-right">
                  <button class="inline-block px-4 py-2 bg-blue-600 text-white rounded-md" @click="copyDetail">复制</button>
                </div>
              </div>
            </div>
          </div>

        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute } from '#imports'
import { useHead } from '#imports'

useHead({ title: '支付结果 - 八八小店' })

const route = useRoute()
const loading = ref(true)
const error = ref('')
// 支持多条订单结果（通过邮箱查询可能返回多条）
const orders = ref([]) // 当返回多条时使用
const selectedOrder = ref(null) // 当前选中的订单对象
const order = ref({}) // 兼容老代码：单条订单时也能使用
const productInfoHtml = ref('')
const parsedProduct = ref(null) // 若为数组则为数组
const parsedProductObj = ref(null) // 若为单对象则在这里

// 查询表单字段
const inputPaymentNo = ref('')
const inputEmail = ref('')

const displayedOrder = computed(() => {
  // 优先使用 selectedOrder，其次 orders[0]，最后回退到老的 order
  return selectedOrder.value ?? (orders.value && orders.value.length ? orders.value[0] : order.value)
})

const detailText = computed(() => {
  return displayedOrder.value ? displayedOrder.value.product_info : ''
})

async function fetchOrderByTradeNo(payload) {
  try {
    // payload 可以是字符串（payment_no）或者对象 { payment_no, email }
    const body = (typeof payload === 'object' && payload !== null)
      ? { payment_no: payload.payment_no || null, email: payload.email || null }
      : { payment_no: payload }

    const res = await fetch('/api/getorder', {
      method: 'POST', headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(body)
    })
    const json = await res.json()
    return json
  } catch (e) {
    return { status: 500, message: String(e) }
  }
}

function tryParseProductInfo(raw) {
  parsedProduct.value = null
  parsedProductObj.value = null
  productInfoHtml.value = raw == null ? '' : ''
}

async function copyDetail() {
  const text = detailText.value || ''
  try {
    if (navigator.clipboard && navigator.clipboard.writeText) {
      await navigator.clipboard.writeText(text)
    } else {
      const ta = document.createElement('textarea')
      ta.value = text
      document.body.appendChild(ta)
      ta.select()
      document.execCommand('copy')
      ta.remove()
    }
    // 简单反馈
    window.alert('订单详情已复制')
  } catch (e) {
    window.alert('复制失败')
  }
}


onMounted(async () => {
  const q = route.query || {}
  const payment_no = q.trade_no || q.tradeNo || q.payment_no || q.paymentNo
  // 预填表单
  inputPaymentNo.value = payment_no || ''

  // 如果路由中有支付单号则自动查询，否则显示空表单供手动查询
  if (!payment_no) {
    loading.value = false
    return
  }

  // 自动查询
  try {
    loading.value = true
    error.value = ''
    const ord = await fetchOrderByTradeNo(payment_no)
    if (ord.status !== 200 || !ord.data) {
      error.value = ord.message || '未找到订单或查询出错'
      loading.value = false
      return
    }
    // 支持后端返回数组或单对象
    if (Array.isArray(ord.data)) {
      orders.value = ord.data
      selectedOrder.value = orders.value[0] ?? null
      order.value = selectedOrder.value || {}
    } else {
      orders.value = []
      selectedOrder.value = ord.data
      order.value = ord.data || {}
    }
    const raw = displayedOrder.value ? displayedOrder.value.product_info : null
    tryParseProductInfo(raw)
  } finally {
    loading.value = false
  }
})

// 点击“查询订单”按钮
async function queryOrder() {
  error.value = ''
  const payload = { payment_no: inputPaymentNo.value || null, email: inputEmail.value || null }
  if (!payload.payment_no && !payload.email) {
    error.value = '请输入支付单号或邮箱后查询'
    return
  }

  loading.value = true
  try {
    const ord = await fetchOrderByTradeNo(payload)
    if (ord.status !== 200 || !ord.data) {
      error.value = ord.message || '未找到订单或查询出错'
      return
    }
    if (Array.isArray(ord.data)) {
      orders.value = ord.data
      selectedOrder.value = orders.value[0] ?? null
      order.value = selectedOrder.value || {}
    } else {
      orders.value = []
      selectedOrder.value = ord.data
      order.value = ord.data || {}
    }
    const raw = displayedOrder.value ? displayedOrder.value.product_info : null
    tryParseProductInfo(raw)
  } catch (e) {
    error.value = String(e)
  } finally {
    loading.value = false
  }
}

function clearForm(){
  inputPaymentNo.value = ''
  inputEmail.value = ''
}

// 用户从列表中选择一条订单以查看详情
function selectOrder(index){
  const o = orders.value && orders.value[index]
  if (o) {
    selectedOrder.value = o
    order.value = o
    // 重新解析 product_info
    tryParseProductInfo(o.product_info)
    // 滚动到详情区（可选）
    setTimeout(()=>{
      const el = document.querySelector('.detail-card')
      if (el && el.scrollIntoView) el.scrollIntoView({ behavior: 'smooth', block: 'center' })
    },50)
  }
}
</script>

<style scoped>
/* 页面整体样式 */
.result-page{
  padding:24px;
  background: linear-gradient(180deg,#f6f9ff 0%, #f3f6ff 100%);
  min-height:360px;
  color:#2c3e50;
}
.result-page h1{ font-size:18px; margin:6px 0 14px 0; color:#263248 }
.error{ color:#e55353 }

/* 两栏布局 */
.order-container{ display:flex; gap:20px; align-items:flex-start; margin-top:12px }
.left{ flex:1 }
.right{ width:360px; max-width:38% }

/* 卡片样式 */
.order-card, .detail-card{
  background:#fff;
  border-radius:10px;
  padding:18px;
  box-shadow:0 6px 18px rgba(40,44,63,0.06);
  border:1px solid rgba(15,23,42,0.04);
}
.order-title{ margin:0 0 8px 0; font-size:15px; color:#1f2d3d }
.meta div{ margin:8px 0; color:#4b5563 }
.meta strong{ color:#111827 }

.product-info{ margin-top:12px }
.product-info h4{ margin:0 0 10px 0; font-size:14px; color:#233044 }

.product-list{ list-style:none; padding:0; margin:0; display:flex; flex-direction:column; gap:10px }
.product-item{ display:flex; gap:12px; align-items:center; border-radius:8px; padding:10px; background:linear-gradient(180deg,#ffffff,#fbfdff) }
.product-item .thumb{ width:64px; height:64px; object-fit:cover; border-radius:6px; border:1px solid #f0f3f8 }
.p-body{ flex:1 }
.p-name{ font-weight:600; color:#162033 }
.p-meta{ color:#6b7280; font-size:13px; margin-top:6px }
.raw-html{ margin-top:8px; color:#334155 }
.empty{ color:#9ca3af; padding:10px }

.kv{ width:100%; border-collapse:collapse }
.kv td.k{ width:30%; padding:8px; background:#fbfbfe; color:#374151; font-weight:600 }
.kv td.v{ padding:8px; color:#475569 }

.detail-area{ width:100%; height:220px; resize:vertical; padding:12px; border:1px solid #e6eef8; border-radius:8px; font-family:ui-monospace,monospace; background:#fbfdff }
.actions{ margin-top:12px; text-align:right }
.btn{ background:linear-gradient(180deg,#2b7cff,#166fde); color:#fff; border:none; padding:8px 14px; border-radius:6px; cursor:pointer; box-shadow:0 6px 12px rgba(43,124,255,0.12) }
.btn:hover{ transform:translateY(-1px) }

/* 让右侧卡片标题更突出 */
.detail-card h4{ margin:0 0 8px 0; font-size:14px; color:#243447 }

@media (max-width:980px){
  .order-container{ flex-direction:column }
  .right{ width:100%; max-width:100% }
}

</style>
